import json
import time
from utils.AssertUtil import AssertUtil
from utils.YAMLUtil import YamlUtils
from utils.log_util import logger


class ExtractUtil:
    def __init__(self):
        self.jsonpath_util = AssertUtil()
        self.yaml_util = YamlUtils()
    def extract_data(self,res,extract):
        """
        根据extract表达式获取接口内容并存入yaml
        :param res: res.json()
        :param extract:  例如: $.token
        :return:
        """
        if extract:
            for key,expression in extract.items():
                try:
                    value = self.jsonpath_util.extract_by_jsonpath(res,expression)
                     # 写入value
                    self.yaml_util.write_extra_yaml({key:value})
                except Exception as e:
                    logger.error(f"变量{key}写入extract.yaml失败，请检查，error={e}")


    def get_extract_value(self,key):
        """从extract.yaml中获取内容"""
        try:
            data = self.yaml_util.read_extract_yaml()
            return data[key]
        except Exception as e:
            logger.error(f"从yaml中根据{key}获取不到内容，error={e}")


    def extract_url(self, url):
       # / orders /${get_extract_value(order_id)} /
        if "{" and "}" in url:
            return self.process_data(url)
        return url

    def process_data(self,data):
        """处理函数"""
        for i in range(data.count("${")):
            if "{" and "}" in data:
                start_index = data.index("$")
                end_index = data.index("}")
                # 获取函数中的方法
                func_full_name = data[start_index :end_index + 1]
                # 获取函数名
                func_name = data[start_index + 2 :data.index('(')]
                # 获取函数参数
                func_params = data[data.index('(') + 1 :data.index(')')]
                # 不支持函数参数为int类型
                extract_data = getattr(self,func_name)(*func_params.split(',') if func_params else "")
                data = data.replace(func_full_name,str(extract_data))
        return data
    def extract_case(self,case_info):
        # 转换成str类型
        str_case_info = json.dumps(case_info)
        data = self.process_data(str_case_info)
        # 转换成json类型
        return json.loads(data)

    # 获取时间戳
    def get_time(self):
        timestamp = int(time.time() )
        return timestamp


if __name__ == '__main__':
    print(ExtractUtil().get_time())
    # print(ExtractUtil().get_extract_value())
    # print(getattr(ExtractUtil(),"get_extract_value")("1111"))